// 菜单初始化

import { getMenuTreeByRoleKey } from '@/api/upms/menu'
import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    console.log('ff', state.routes)
  }
}

const actions = {
  // 根据用户角色获取用户菜单
  getMenuTreeByRoleKey({ commit }) {
    return new Promise((resolve, reject) => {
      const loadMenuData = []
      getMenuTreeByRoleKey().then(resp => {
        if (resp.code !== 0) {
          this.notifyErr('菜单获取失败')
          reject()
        } else {
          // 组装菜单
          Object.assign(loadMenuData, resp.data.list) // 拷贝
          generaMenu(asyncRoutes, loadMenuData)
          asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', asyncRoutes)
          resolve(asyncRoutes)
        }
      })
    })
  }
}

// 生成路由
export function generaMenu(routes, data) {
  data.forEach(item => {
    const menu = {
      path: item.path,
      component: item.componentPath === 'Layout' ? Layout : loadView(item.componentPath), // 加载组件
      hidden: item.isVisible !== '1',
      name: item.routeName,
      meta: {
        title: item.menuTitle,
        icon: item.icon
        // noCache: true
      },
      children: []
    }
    if (item.children && item.children.length > 0) {
      generaMenu(menu.children, item.children)
    }
    routes.push(menu)
  })
}
export const loadView = (view) => { // 路由懒加载
  return (resolve) => require(['@/views/upms' + view], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
